import { reactive, toRefs, computed } from "vue"
import { onShow, onUnload, onReady, onLoad } from "@dcloudio/uni-app";
import { LoginStore } from "@/store/modules/login";
const uniIdCo = uniCloud.importObject("uni-id-co", { customUI: true })
/**
 * @description  修改密码
 * @param rules 表单校验规则
 * */
export const useUpdatePwd = (formRefs, rules) => {
	const state = reactive({
		formDatas: {
			oldPassword: "", //旧密码
			newPassword: '' //新密码
		},
		formItems: {
			loading: false, //防抖状态
		},
		// 校验规则
		rules
	})
	onLoad((e) => {

	})
	// 兼容H5
	onShow(() => {
		// #ifdef H5
		document.onkeydown = event => {
			var e = event || window.event;
			if (e && e.keyCode == 13) { //回车键的键值为13
				submit()
			}
		};
		// #endif
	})
	onReady(() => {
		// 兼容小程序的校验 (uview中使用)
		if (formRefs.value.setRules) formRefs.value.setRules(state.rules)
	});


	// 卸载键盘事件
	onUnload(() => {
		// #ifdef H5
		document.onkeydown = false
		// #endif
	});
	/**
	 * @description: 设置密码
	 * @param {*} formRef 表单实例
	 * @param {*} rules 验证规则
	 */
	const updatePwd = async () => {
		return new Promise((resolve, reject) => {
			formRefs.value.validator(state.formDatas, rules).then(async res => {
				if (!res.isPassed) return
				try {
					state.formItems.loading = true
					const res = await uniIdCo.updatePwd({
						oldPassword: state.formDatas.oldPassword,
						newPassword: state.formDatas.newPassword,
					})
					if (res.errCode == 0) {
						uni.fui.toast('修改成功')
						state.formItems.loading = false
						state.formDatas.oldPassword = ""
						state.formDatas.newPassword = ""
						const LoginState = LoginStore()
						LoginState.logout()
					}
					resolve(res)
				} catch (e) {
					uni.fui.toast(e.errMsg)
					state.formItems.loading = false
					reject({...e})
				}
			})
		})
	}
	return {
		...toRefs(state),
		updatePwd
	};
};